// ==UserScript==
// @name        有赞客户信息导出
// @namespace   Violentmonkey Scripts
// @match       https://crm.youzan.com/crm/member/import#/detail*
// @grant       none
// @version     1.0
// @author      jialesmile
// @description 2024/8/5 16:41:01
// @updateURL   https://gitee.com/tangjiale/tampermonkey/raw/master/youzan/youzan_member_export.js
// @downloadURL https://gitee.com/tangjiale/tampermonkey/raw/master/youzan/youzan_member_export.js
// ==/UserScript==
(function () {

    // 在页面加载完成后执行代码
    window.onload = function () {
        console.log("客户列表导出插件加载成功")

        // 添加自定义CSS
        addCustomCSS();

        // 获取需要插入按钮的div元素
        const targetDiv = document.querySelector('._1lrPs')

        // create button element
        const button = document.createElement('button');
        button.innerText = '导出数据';
        button.classList.add("custom-button")
        // add click event
        button.addEventListener('click', function () {
            const params = getQueryParams();
            const importId = params['importId'];

            // 获取用户信息
            getAllUserDataList(1, 50, [], importId)
                .then(function (response) {
                    // console.log("当前的列表数据=" + JSON.stringify(response))
                    // 导出excel
                    exportToExcel(response)
                })
                .catch(function (error) {
                    console.log(error);
                });
        });
        // button insert to div element
        // targetDiv.appendChild(button);
        targetDiv.insertAdjacentElement("afterbegin", button)
    }

// 异步获取所有的数据
    async function getAllUserDataList(page = 1, pageSize = 50, list = [], importId) {
        try {
            const data = await getUserDataList(page, pageSize, importId);

            // Check if the necessary properties are defined
            if (data && data.data && Array.isArray(data.data.importRowDTOList)) {
                if (data.data.importRowDTOList.length > 0) {
                    // Merge the current page's data with the accumulated list
                    // list = [...list, ...data.data.importRowDTOList];
                    // 处理需要的数据
                    list = [...list, ...data.data.importRowDTOList.map(item => ({
                        "用户手机号": item.userMobile,
                        "姓名": item.columnFieldMap.name?.value || "",
                        "积分": item.columnFieldMap.points?.value || "",
                        "储值本金": item.columnFieldMap.prepaid_balance?.value || "",
                        "储值赠送金": item.columnFieldMap.prepaid_balance_bonus?.value || "",
                        // "状态": item.status,
                        "分组标签": item.columnFieldMap.salesman_tags?.value || ""
                    }))];
                    page++; // Increment the page number
                    // Recursively fetch the next page
                    return getAllUserDataList(page, pageSize, list, importId);
                }
            } else {
                // No more data or data format is unexpected, return the accumulated list
                return list;
            }
        } catch (error) {
            console.error('Error fetching user data:', error);
            throw error; // Rethrow the error for handling upstream
        }
    }


// 获取用户列表信息
    function getUserDataList(page, pageSize, importId) {
        return new Promise(function (resolve, reject) {
            const xhr = new XMLHttpRequest();
            const url = `https://crm.youzan.com/crm/member/import/api/getTaskDetailList?page=${page}&pageSize=${pageSize}&importId=${importId}&result=&identityValue=`;
            xhr.open('GET', `${url}`, true);
            xhr.setRequestHeader('Content-type', 'application/json');
            xhr.send();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        const response = JSON.parse(xhr.responseText);
                        console.log(response)
                        resolve(response);
                    } else {
                        reject(xhr.status);
                    }
                }
            }
        });

    }


// 导出excel功能
    function exportToExcel(jsonData) {
        // 将JSON数据转换为CSV格式
        const csv = jsonToCsv(jsonData);

        // 创建一个Blob对象，并添加BOM以确保Excel正确识别UTF-8编码
        const bom = '\ufeff'; // BOM for UTF-8
        const blob = new Blob([bom + csv], {type: 'text/csv;charset=utf-8;'});

        // 创建一个下载链接
        const link = document.createElement("a");
        const url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", "data.csv");
        document.body.appendChild(link);

        // 模拟点击以触发下载
        link.click();

        // 移除链接
        document.body.removeChild(link);
    }

// json 转csv
    function jsonToCsv(jsonData) {
        const csvRows = [];
        // 获取表头
        const headers = Object.keys(jsonData[0]);
        csvRows.push(headers.join(','));

        // 添加数据行
        for (const row of jsonData) {
            const values = headers.map(header => {
                const escaped = ('' + row[header]).replace(/"/g, '\\"');
                return `"${escaped}"`;
            });
            csvRows.push(values.join(','));
        }

        return csvRows.join('\n');
    }

// 添加自定义css样式
    function addCustomCSS() {
        const style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = `
    .custom-button {
      background-color: red;
      color: white;
      border: none;
      padding: 8px 16px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 14px;
      margin: 4px 2px;
      cursor: pointer;
      border-radius: 4px;
    }
  `;
        document.head.appendChild(style);
    }

// 获取当前页面的url参数
    function getQueryParams() {
        const params = {};
        const hash = window.location.hash;
        const queryString = hash.includes('?') ? hash.split('?')[1] : '';

        if (!queryString) {
            console.log("No query string found in the URL");
            return params;
        }

        const vars = queryString.split('&');
        vars.forEach((pair) => {
            const [key, value] = pair.split('=');
            if (key && value) {
                params[key] = decodeURIComponent(value);
            }
        });
        return params;
    }

// 合并json
    function mergeJson(json1, json2) {
        const result = {...json1};

        for (const key in json2) {
            if (json2.hasOwnProperty(key)) {
                if (result[key] && typeof result[key] === 'object' && typeof json2[key] === 'object') {
                    result[key] = mergeJson(result[key], json2[key]);
                } else {
                    result[key] = json2[key];
                }
            }
        }

        return result;
    }


})();